package org.stars.dao.sqlmapper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Text;

public class SqlBase implements Serializable, Cloneable  {
	private static final long serialVersionUID = 969044322903842883L;

	@Attribute(name="id",required=true)
	protected String id;
	
	protected List<SqlFragment> parts;
	
	protected SqlMapper sqlMapper;
	
	protected List<Parameter> parameters;
	
	public List<Parameter> getParameters() {
		return parameters;
	}

	public void setParameters(List<Parameter> parameters) {
		this.parameters = parameters;
	}

	@Text(data=true, required=false)
	protected String templateText;

	@Override
	public SqlBase clone() {
		SqlBase newObject=new SqlBase();
		
		copyValues(newObject);
		
		return newObject;
    }
	
	protected void copyValues(SqlBase newObject)
	{
		newObject.setId(id);
		newObject.setSqlMapper(sqlMapper);
		newObject.setTemplateText(templateText);
		
		for(Parameter item: parameters)
		{
			newObject.getParameters().add(item.clone());
		}
		
		SqlFragment newListItem=null;		
		for(SqlFragment item: parts)
		{
			newListItem=item.clone();
			newObject.getParts().add(newListItem);
		}
	}
	
	/**
	 * Necessary for read config from xml
	 */
	public SqlBase()
	{
		this.parts=new ArrayList<SqlFragment>();
		this.parameters=new ArrayList<Parameter>();
	}
	
	public SqlBase(SqlMapper sqlMapper, String id, String simpleText)
	{
		this();
		this.sqlMapper=sqlMapper;
		this.id=id;
		this.templateText=simpleText;		
	}

	public String getId() {
		return id;
	}

	public List<SqlFragment> getParts() {
		return parts;
	}

	public SqlMapper getSqlMapper() {
		return sqlMapper;
	}
	
	public String getTemplateText() {
		return templateText;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setParts(List<SqlFragment> parts) {
		this.parts = parts;
	}

	public void setSqlMapper(SqlMapper sqlMapper) {
		this.sqlMapper = sqlMapper;
	}

	public void setTemplateText(String simpleText) {
		this.templateText = simpleText;
	}
	
	@Override
	public String toString()
	{
		if (parts.size()==0)
			return templateText;
		
		StringBuilder sb=new StringBuilder();
		for (SqlFragment item: parts)
		{
			sb.append(item.toString());
		}
		
		return sb.toString();
	}
	
}
